

package MOL;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * @author czx
 *
 */
public class UserDaoJDBC implements UserDao {


	@Override
	public User readUser(String userName) {
		Connection conn = null;
		PreparedStatement pstat = null;
		ResultSet rs = null;
		String sql = "select * from usere where userName like ? ";//表中有id和name这列
		User use = null;
		try {
			conn = uil.JDBCUtil.getConnection();
			pstat = conn.prepareStatement(sql);
			pstat .setString(1, userName);
			rs = pstat.executeQuery();
			while(rs.next()){
				String userName1= rs.getString("userName");
				String  password1 = rs.getString("password");
				 use = new User (userName1, password1);
			}
		}catch (SQLException sqle) {
			sqle.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			uil.JDBCUtil.realeaseAll(rs,pstat, conn);
		}
		return use;
	
	}

	@Override
	public void diplayAllUser() {
		Connection conn = null;
		Statement stat = null;
		ResultSet rs = null;
		String sql = "select * from user";
		try {
			conn = uil.JDBCUtil.getConnection();
			stat = conn.createStatement();
			rs = stat.executeQuery(sql);
			while(rs.next()){
				String userName= rs.getString("userName");
				String  password = rs.getString("password");
				System.out.format("该学生的 userName=%s, userName=%s\n", userName,password);
			}
		}catch (SQLException sqle) {
			sqle.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			uil.JDBCUtil.realeaseAll(rs,stat, conn);
		}
		
	}

	@Override
	public boolean writeUser(User user) {
		Connection conn = null;
		PreparedStatement pstat = null;
		String sql = "insert into user(userName,password) values(?,?) ";
		int result = -1;
		
		try {
			conn = uil.JDBCUtil.getConnection();
			pstat = conn.prepareStatement(sql);
			pstat.setString(1, user.getUserName());
			pstat.setString(2, user.getUserName());
			result = pstat.executeUpdate();
			
		}catch (SQLException sqle) {
			sqle.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			uil.JDBCUtil.realeaseAll(null,pstat, conn);
		}
		return result>0?true:false;
	
	}
	

}
